import { RouteRecordRaw } from "vue-router";
/**
 * 根据用户权限过滤路由
 * @notes 没有roles默认为有权限（后端返回路由都已根据角色进行过滤，前端不做过滤也可以）
 * @param route - 权限路由
 * @param roles - 权限
 */
function hasPermission(route: RouteRecordRaw, role: Array<string>) {
  return (
    !route.meta?.roles ||
    role.some((item) => {
      (route.meta?.roles as string[]).includes(item);
    })
  );
}

/** 递归过滤异步路由表，筛选角色权限路由
 * @param routes - 权限路由组
 * @param roles - 权限
 */
export function filterRoutesByRole(
  routes: RouteRecordRaw[],
  role: Array<string>
) {
  const res: RouteRecordRaw[] = [];
  routes.forEach((route: RouteRecordRaw) => {
    const tmp = { ...route };
    if (hasPermission(tmp, role)) {
      if (tmp.children) {
        tmp.children = filterRoutesByRole(tmp.children, role);
      }
      res.push(tmp);
    }
  });
  return res;
}
